﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Box.Entities;
namespace Box.Repository
{
    public class ClienteRepository : MasterRepository, IClienteRepository
    {
        public List<Cliente> GetAllFromClientes()
        {
            var query = (from c in Context.Clientes
                        select c).Take(20);
            return query.ToList();
        }

        public List<Cliente> GetFromClientesByCriterio(string criterio)
        {
            var query = (from c in Context.Clientes
                        select c).Take(20);
            if (criterio != null && criterio != string.Empty)
            {
                query = from c in query
                        where c.NombreCliente.ToUpper().Contains(criterio.ToUpper())
                             
                        select c;
            }
            return query.ToList();
        }

        public Cliente GetFromClienteByDni(string dni)
        {
            try
            {
                var query = from p in Context.Clientes
                            select p;
                if (dni!=null && dni!=string.Empty)
                {
                    query = (from p in query
                        where p.RucCliente.Equals(dni)
                        select p).Take(20);

                }
                return query.SingleOrDefault();
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
            
        }

        public Cliente GetFromClienteById(int id)
        {
            var query = from p in Context.Clientes
                        where p.Id.Equals(id)
                        select p;
            
            return query.SingleOrDefault();
        }

        public void AddCliente(Cliente cliente)
        {
            Context.Clientes.Add(cliente);
            Context.SaveChanges();
        }

        public void UpdateCliente(Cliente cliente)
        {
            Context.Entry(cliente).State = EntityState.Modified;
            Context.SaveChanges();
        }

        public void RemoveCliente(int id)
        {
            var existe = Context.Clientes.Find(id);
            if (existe != null)
            {
                Context.Clientes.Remove(existe);
                Context.SaveChanges();
            }
        }
    }
}
